package com.liuqi.openai.data.document.splitter;

import com.liuqi.openai.data.document.Document;
import com.liuqi.openai.data.document.DocumentSplitter;
import com.liuqi.openai.data.document.Metadata;
import com.liuqi.openai.data.segment.TextSegment;
import java.util.ArrayList;
import java.util.List;

import static com.liuqi.openai.util.ValidationUtil.ensureNotNull;

/**
 * 混合文档分割
 *
 * @author liuqi
 * @date 2025/8/11
 **/
public abstract class HybridDocumentSplitter implements DocumentSplitter {

    protected final DocumentSplitter subSplitter;

    public HybridDocumentSplitter(DocumentSplitter subSplitter) {
        this.subSplitter = subSplitter;
    }

    @Override
    public List<TextSegment> split(Document document) {
        ensureNotNull(document, "document");

        List<TextSegment> segments = new ArrayList<>();

        String[] parts = split(document.text());

        for (String part : parts) {
            if (subSplitter != null) {
                List<TextSegment> subTs = subSplitter.split(Document.from(part));
                segments.addAll(subTs);
            } else {
                segments.add(createSegment(part, document));
            }
        }

        return segments;
    }

    protected abstract String[] split(String text);

    public static TextSegment createSegment(String text, Document document) {
        Metadata metadata = document.metadata().copy();
        return TextSegment.from(text, metadata);
    }
}
